package yxy.game.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class HttpHelper {

	public static String doGet(String url) {
		return doGet(url, null);
	}

	public static String doGet(String url, JSONObject headobj) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url);
			System.out.println("executing request " + httpget.getURI());
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				if (headobj != null) {
					Set<String> keys = headobj.keySet();
					for (String key : keys) {
						httpget.setHeader(key, headobj.getString(key));

					}
				}
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				System.out.println("--------------------------------------");
				// 打印响应状态
				System.out.println(response.getStatusLine());
				if (entity != null) {
					// 打印响应内容长度
					System.out.println("Response content length: " + entity.getContentLength());
					// 打印响应内容
					String ret = EntityUtils.toString(entity, "UTF-8");
					System.out.println("Response content: " + ret);
					return ret;
				}
				System.out.println("------------------------------------");
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	public static byte[] doGet2(String url) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url);
			System.out.println("executing request " + httpget.getURI());
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			// 获取响应实体
			HttpEntity entity = response.getEntity();
			System.out.println("--------------------------------------");
			// 打印响应状态
			System.out.println(response.getStatusLine());
			if (entity != null) {
				// 打印响应内容长度
				System.out.println("Response content length: " + entity.getContentLength());
				// 打印响应内容
				int len = (int) entity.getContentLength();
				InputStream is = entity.getContent();
				byte[] b = null;

				if (len >= 0) {
					b = new byte[len];
					int off = 0;
					while (off < entity.getContentLength()) {
						int read = is.read(b, off, len - off);
						if (read < 0)
							throw new IOException();
						off += read;
					}
				} else {
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					b = new byte[4096];
					for (;;) {
						int read = is.read(b, 0, b.length);
						if (read < 0)
							break;
						baos.write(b, 0, read);
					}
					baos.close();
					b = baos.toByteArray();
				}

				if (response != null)
					response.close();

				return b;
			}
			System.out.println("------------------------------------");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	/**
	 * 发送 POST 请求（HTTP），K-V形式
	 * 
	 * @param apiUrl
	 *            API接口URL
	 * @param params
	 *            参数map
	 * @return
	 */
	public static String doPost(String apiUrl, NameValuePair[] params, int timeout) {
		return doPost(apiUrl, params, timeout, null);
	}

	public static String doPost(String apiUrl, NameValuePair[] params, int timeout, JSONObject headobj) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String httpStr = null;
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;

		try {
			if (headobj != null) {
				Set<String> keys = headobj.keySet();
				for (String key : keys) {
//					httpPost.setHeader(key, headobj.getString(key));
					httpPost.addHeader(key, headobj.getString(key));
				}
			}
			// -----------------
			RequestConfig.Builder configBuilder = RequestConfig.custom();
			// 设置连接超时
			configBuilder.setConnectTimeout(timeout);
			// 设置读取超时
			configBuilder.setSocketTimeout(timeout);
			// 设置从连接池获取连接实例的超时
			configBuilder.setConnectionRequestTimeout(timeout);
			// 在提交请求之前 测试连接是否可用
			configBuilder.setStaleConnectionCheckEnabled(true);
			httpPost.setConfig(configBuilder.build());
			// --------------
			List<NameValuePair> pairList = new ArrayList<NameValuePair>();
			if (params != null) {
				for (int i = 0; i < params.length; i++)
					pairList.add(params[i]);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			httpStr = EntityUtils.toString(entity, "UTF-8");
		} catch (IOException e) {
//			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	public static byte[] doPost2(URL url, String contentType, byte[] outdata) throws IOException {

		HttpURLConnection http = (HttpURLConnection) url.openConnection();
		http.setRequestProperty("Content-Type", contentType);
		http.setRequestProperty("Content-Length", String.valueOf(outdata.length));
		http.setDoOutput(true);
		http.setDoInput(true);
		http.setConnectTimeout(30000);
		http.connect();
		OutputStream outs = http.getOutputStream();
		outs.write(outdata);
		outs.close();
		int code = http.getResponseCode();
		if (code != 200) {
			throw new IOException("Bad RPC '" + url.toString() + "': " + code);
		}
		InputStream stream = http.getInputStream();
		try {
			int len = http.getContentLength();
			byte[] data;
			if (len >= 0) {
				data = new byte[len];
				int off = 0;
				while (off < len) {
					int read = stream.read(data, off, len - off);
					if (read < 0)
						throw new IOException();
					off += read;
				}
			} else {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[4096];
				for (;;) {
					int read = stream.read(buffer, 0, buffer.length);
					if (read < 0)
						break;
					baos.write(buffer, 0, read);
				}
				baos.close();
				data = baos.toByteArray();
			}
			return data;
		} finally {
			stream.close();
			http.disconnect();
		}
	}

	public static NameValuePair[] getValuePair(JSONObject parseobj) {
		NameValuePair[] pair = new NameValuePair[parseobj.size()];

		Set<String> set = parseobj.keySet();
		int i = 0;
		for (String key : set) {
			pair[i] = new BasicNameValuePair(key, parseobj.getString(key));
			i++;
		}
		return pair;
	}
	
}
